<template>
  <div>
    <div v-if="viewMode" class="text-right mb-2">
      <el-button size="small" icon="el-icon-printer" @click="handlePrint">打印</el-button>
    </div>
    <div id="print-wrap" v-loading="loading">
      <h5 class="text-center">担保项目审批（评审）表</h5>
      <table class="table table-sm table-bordered vertical-align-middle text-center">
        <tbody>
          <tr>
            <td width="25%">借款人名称</td>
            <td colspan="3">{{ related.customer_name || relatedData.customer_name }}</td>
          </tr>
          <tr>
            <td>申请金额</td>
            <td width="25%">{{ related.apply_funds }}万元</td>
            <td width="25%">申请期限</td>
            <td width="25%">{{ related.load_years }}年</td>
          </tr>
          <tr>
            <td>贷款实际用途</td>
            <td>{{ related.funds_use_dir }}</td>
            <td>法定代表人</td>
            <td>{{ related.corp_name || relatedData.corp_name }}</td>
          </tr>
          <tr>
            <td>贷款银行</td>
            <td>{{ related.bank_name }}</td>
            <td>贷款利率（年）</td>
            <td class="report-input-td">
              <span v-if="isCountyViewMode">{{ data.load_rate || '-' }}%</span>
              <el-input v-else placeholder="贷款利率（年）" type="number" v-model="data.load_rate">
                <span slot="append">%</span>
              </el-input>
            </td>
          </tr>
          <tr>
            <td>
              <span v-if="isAbApproval">建议金额</span>
              <span v-else>审批金额</span>
            </td>
            <td class="report-input-td">
              <span v-if="isCountyViewMode || !isAbApproval">{{ data.res_funds || '-' }}万元</span>
              <!--
                change: 20200909
              -->
              <el-input
                v-else
                v-input-number="{ min: 0, fixed: 2 }"
                placeholder="建议金额"
                v-model="data.approved_funds"
              >
                <span slot="append">万元</span>
              </el-input>
            </td>
            <td>期限</td>
            <td class="report-input-td">
              <span v-if="isCountyViewMode">{{ data.approval_load_years || '-' }}年</span>
              <el-input
                v-else
                type="number"
                placeholder="审批期限"
                :min="0"
                v-model="data.approval_load_years"
              >
                <span slot="append">年</span>
              </el-input>
            </td>
          </tr>
          <tr>
            <td>担保费率</td>
            <td class="report-input-td">
              <span v-if="isCountyViewMode">{{ data.gua_rate || '-' }}%</span>
              <el-input v-else type="number" placeholder="担保费率" v-model="data.gua_rate">
                <span slot="append">%</span>
              </el-input>
            </td>
            <td>评审费</td>
            <td class="report-input-td">
              <span v-if="isCountyViewMode">{{ data.approval_fee || '-' }}元</span>
              <el-input
                v-else
                type="number"
                placeholder="评审费"
                :min="0"
                v-model="data.approval_fee"
              >
                <span slot="append">元</span>
              </el-input>
            </td>
          </tr>
          <tr>
            <td>项目主审</td>
            <td>{{ related.res_a_name }}</td>
            <td>项目辅审</td>
            <td>{{ related.res_b_name }}</td>
          </tr>
          <tr>
            <td>反担保措施</td>
            <td colspan="3" class="report-input-td text-left">
              <div v-if="isCountyViewMode" style="text-indent: 2rem" class="p-2">
                {{ data.counter_guarantee || '-' }}
              </div>
              <textarea
                v-else
                rows="4"
                class="form-control"
                v-model="data.counter_guarantee"
              ></textarea>
            </td>
          </tr>
          <tr>
            <td>项目基本介绍</td>
            <td colspan="3" class="report-input-td text-left">
              <div v-if="isCountyViewMode" style="text-indent: 2rem" class="p-2">
                {{ data.project_des || '-' }}
              </div>
              <textarea v-else rows="4" class="form-control" v-model="data.project_des"></textarea>
            </td>
          </tr>
          <tr>
            <td>项目经理意见</td>
            <td colspan="3" class="report-input-td text-left">
              <textarea
                rows="4"
                v-if="editEnableAb && !isCountyViewMode"
                class="form-control"
                v-model="data.res_option"
              ></textarea>
              <div v-else class="p-2">
                <p style="text-indent: 2rem">{{ data.res_option || '-' }}</p>
                <div class="d-flex justify-content-between">
                  <div>项目经理A、B角签字：{{ data.res_person }}</div>
                  <div>{{ $utils.dateFormat(data.res_date, 'yyyy年MM月dd日') }}</div>
                </div>
              </div>
            </td>
          </tr>
          <template v-if="isAutoApprovalProject">
            <tr>
              <td>业务部意见</td>
              <td colspan="3" class="report-input-td text-left">
                <textarea
                  rows="4"
                  v-if="editEnableBusiness && !isCountyViewMode"
                  class="form-control"
                  v-model="data.res_option_bus"
                ></textarea>
                <div v-else class="p-2">
                  <p style="text-indent: 2rem">{{ data.res_option_bus || '-' }}</p>
                  <div class="d-flex justify-content-between">
                    <div>签字：{{ data.res_person_bus }}</div>
                    <div>{{ $utils.dateFormat(data.res_date_bus, 'yyyy年MM月dd日') }}</div>
                  </div>
                </div>
              </td>
            </tr>
            <tr>
              <td>风控部意见</td>
              <td colspan="3" class="report-input-td text-left">
                <textarea
                  rows="4"
                  v-if="editEnableRisk && !isCountyViewMode"
                  class="form-control"
                  v-model="data.res_option_risk"
                ></textarea>
                <div v-else class="p-2">
                  <p style="text-indent: 2rem">{{ data.res_option_risk || '-' }}</p>
                  <div class="d-flex justify-content-between">
                    <div>签字：{{ data.res_person_risk }}</div>
                    <div>{{ $utils.dateFormat(data.res_date_risk, 'yyyy年MM月dd日') }}</div>
                  </div>
                </div>
              </td>
            </tr>
            <tr>
              <td>负责人意见</td>
              <td colspan="3" class="report-input-td text-left">
                <textarea
                  rows="4"
                  class="form-control"
                  v-if="editEnableCorp && !isCountyViewMode"
                  v-model="data.res_option_corp"
                ></textarea>
                <div v-else class="p-2">
                  <p style="text-indent: 2rem">{{ data.res_option_corp || '-' }}</p>
                  <div class="d-flex justify-content-between">
                    <div>签字：{{ data.res_person_corp }}</div>
                    <div>{{ $utils.dateFormat(data.res_date_corp, 'yyyy年MM月dd日') }}</div>
                  </div>
                </div>
              </td>
            </tr>
          </template>
          <template v-else-if="provinceVisible">
            <tr>
              <td>省业务部意见</td>
              <td colspan="3" class="report-input-td text-left">
                <textarea
                  rows="4"
                  class="form-control"
                  v-if="editEnableBusinessProvince"
                  v-model="data.city_res_option_bus"
                ></textarea>
                <div v-else class="p-2">
                  <p style="text-indent: 2rem">{{ data.city_res_option_bus || '-' }}</p>
                  <div class="d-flex justify-content-between">
                    <div>签字：{{ data.city_res_person_bus }}</div>
                    <div>{{ $utils.dateFormat(data.city_res_date_bus, 'yyyy年MM月dd日') }}</div>
                  </div>
                </div>
              </td>
            </tr>
            <tr>
              <td>省风控部意见</td>
              <td colspan="3" class="report-input-td text-left">
                <textarea
                  rows="4"
                  class="form-control"
                  v-if="editEnableRiskProvince"
                  v-model="data.city_res_option_risk"
                ></textarea>
                <div v-else class="p-2">
                  <p style="text-indent: 2rem">{{ data.city_res_option_risk || '-' }}</p>
                  <div class="d-flex justify-content-between">
                    <div>签字：{{ data.city_res_person_risk }}</div>
                    <div>{{ $utils.dateFormat(data.city_res_date_risk, 'yyyy年MM月dd日') }}</div>
                  </div>
                </div>
              </td>
            </tr>
            <tr>
              <td>省负责人意见</td>
              <td colspan="3" class="report-input-td text-left">
                <textarea
                  rows="4"
                  class="form-control"
                  v-if="editEnableCorpProvince"
                  v-model="data.city_res_option_corp"
                ></textarea>
                <div v-else class="p-2">
                  <p style="text-indent: 2rem">{{ data.city_res_option_corp || '-' }}</p>
                  <div class="d-flex justify-content-between">
                    <div>签字：{{ data.city_res_person_corp }}</div>
                    <div>{{ $utils.dateFormat(data.city_res_date_corp, 'yyyy年MM月dd日') }}</div>
                  </div>
                </div>
              </td>
            </tr>
          </template>
        </tbody>
      </table>
    </div>

    <div v-if="editBtnProvinceVisible" class="text-center">
      <el-button class="btn-long" type="primary" @click="handleProvincePass">通过</el-button>
      <el-button class="btn-long" type="danger" @click="handleProvinceReject">不通过</el-button>
    </div>
    <div v-else-if="editBtnCountyVisible" class="text-center">
      <el-button class="btn-long" type="primary" @click="handleCountyPass">通过</el-button>
      <el-button class="btn-long" type="danger" @click="handleCountyReject">不通过</el-button>
    </div>

    <el-dialog
      title="拒绝说明"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="refuseVisible"
      :before-close="refuseBeforeClose"
    >
      <div class="px-5">
        <el-input
          v-model="refuseReason"
          rows="5"
          placeholder="输入拒绝说明"
          type="textarea"
        ></el-input>
      </div>
      <div class="text-center mt-5">
        <el-button type="primary" class="btn-long" @click="handleRefuseConfirm">确定</el-button>
        <el-button class="btn-long" @click="refuseBeforeClose">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { printHtml } from '@vimi/utils-tool'

export default {
  components: {},
  props: {
    viewMode: Boolean,
    relatedData: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      loading: false,
      tableName: 'customer_related',
      related: {},
      data: {},

      refuseReason: '',
      refuseVisible: false,
      refuseType: false,
    }
  },
  computed: {
    ...mapGetters(['userId', 'job', 'user', 'provinceCreditAmount']),

    isUserCounty() {
      return [3, 2].includes(this.user.orgRegionLever)
    },
    isUserProvince() {
      return this.user.orgRegionLever === 1
    },

    isCountyViewMode() {
      return this.viewMode || this.isUserProvince || this.provinceVisible
    },

    // ab角
    isUserAb() {
      return this.userId === this.related.res_a || this.userId === this.related.res_b
    },
    // 业务部员工或负责人
    isUserBusiness() {
      return ['org_c_manage'].includes(this.job)
    },
    // 风控部员工或负责人
    isUserRisk() {
      return ['org_r_manage', 'org_r_emp'].includes(this.job)
    },
    // 负责人
    isUserCorp() {
      return this.job === 'org_corp'
    },

    // 省农担只能由主管审批@twf_20200909
    // 省农担业务部审批人
    isUserBusinessProvince() {
      return ['org_c_manage'].includes(this.job)
    },
    // 省农担风控部审批人
    isUserRiskProvince() {
      return ['org_r_manage'].includes(this.job)
    },
    // 省农担负责人审批人
    isUserCorpProvince() {
      return this.job === 'org_corp'
    },

    // 是否是ab角审批
    isAbApproval() {
      return +this.related.res_status === 0
    },
    // 区县农担 除项目经理外，是否需要填写意见
    editCounty() {
      return this.isUserCounty && this.isAutoApprovalProject
    },
    // 区县农担 项目经理意见是否可编辑
    editEnableAb() {
      return (
        this.isUserCounty &&
        this.isUserAb &&
        (+this.related.res_status === 0 ||
          (+this.related.res_status === 1 && this.related.res_person_user_id === this.userId)) &&
        +this.related.res_status_bus === 0
      )
    },
    // 区县农担 业务部意见是否可编辑
    editEnableBusiness() {
      return (
        this.editCounty &&
        this.isUserBusiness &&
        (this.isUserAb || this.isAbPass) &&
        +this.related.res_status_risk === 0
      )
    },
    // 区县农担 风控部意见是否可编辑
    editEnableRisk() {
      return (
        this.editCounty &&
        this.isUserRisk &&
        +this.related.res_status_bus === 1 &&
        +this.related.res_status_corp === 0
      )
    },
    // 区县农担 负责人意见是否可编辑
    editEnableCorp() {
      return this.editCounty && this.isUserCorp && +this.related.res_status_risk === 1
    },
    // 区县农担 是否审批通过
    isCountyPass() {
      return +this.related.project_res_status === 2
    },
    isAbPass() {
      return +this.related.res_status === 1
    },
    editBtnCountyVisible() {
      return (
        !this.isCountyViewMode &&
        (this.editEnableAb || this.editEnableBusiness || this.editEnableRisk || this.editEnableCorp)
      )
    },

    // 省农担 意见是否可见
    provinceVisible() {
      return !this.isAutoApprovalProject && this.isAbPass
    },
    // 省农担 意见是否编辑
    editProvince() {
      return this.provinceVisible && !this.viewMode && this.isUserProvince
    },
    // 省农担 业务部意见是否可编辑
    editEnableBusinessProvince() {
      return (
        this.editProvince && this.isUserBusinessProvince && +this.related.city_res_status_risk === 0
      )
    },
    // 省农担 风控部意见是否可编辑
    editEnableRiskProvince() {
      return (
        this.editProvince &&
        this.isUserRiskProvince &&
        +this.related.city_res_status_bus === 1 &&
        +this.related.city_res_status_corp === 0
      )
    },
    // 省农担 负责人意见是否可编辑
    editEnableCorpProvince() {
      return (
        this.editProvince && this.isUserCorpProvince && +this.related.city_res_status_risk === 1
      )
    },
    editBtnProvinceVisible() {
      return (
        this.editProvince &&
        (this.editEnableBusinessProvince ||
          this.editEnableRiskProvince ||
          this.editEnableCorpProvince)
      )
    },

    isUnionProvince() {
      return +this.related.gua_type === 4
    },
    isAutoApprovalProject() {
      if (this.isAbApproval) {
        return this.isUnionProvince && +this.data.approved_funds <= this.provinceCreditAmount
      } else {
        return !+this.relatedData.process_status
      }
    },
    relatedId() {
      return this.relatedData.customer_related_id
    },
  },
  watch: {
    relatedData: {
      handler: function () {
        this.getData()
      },
      immediate: true,
      deep: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    async getData() {
      this.loading = true
      if (!this.isAbApproval) {
        await this.$store.dispatch('getProvinceAccessAgency')
      }
      const [res] = await this.$utils.promise(
        Promise.all([this.getRelatedData(), this.getApprovalData()])
      )
      this.loading = false
      const [resRelated, resApproval] = res || []

      this.related = this.getFirstData(resRelated)
      this.data = this.getFirstData(resApproval)
      if (this.isAbApproval) {
        this.setDataValue(
          'approved_funds',
          +this.related.approved_funds || +this.related.apply_funds
        )
      } else {
        this.setDataValue('res_funds', +this.related.res_funds || +this.related.approved_funds)
      }
      this.setDataValue('load_rate', this.related.load_rate)
      this.setDataValue('approval_load_years', this.related.approval_load_years)
      this.setDataValue('gua_rate', this.related.gua_rate)
      this.setDataValue('approval_fee', this.related.approval_fee)
      this.setDataValue('project_des', this.related.project_des || this.related.item_project_des)
      this.setDataValue(
        'counter_guarantee',
        this.related.counter_guarantee || this.related.item_counter_guarantee
      )
    },

    getRelatedData() {
      return this.$api.getData(this.$serviceName, 'customer_related', {
        'customer_related_id.eq': this.relatedId,
      })
    },

    getApprovalData() {
      return this.$api.getData(this.$serviceName, 'customer_approval_view', {
        'customer_related_id.eq': this.relatedId,
      })
    },

    getFirstData(res) {
      return (res && res.data && res.data[0]) || {}
    },

    setDataValue(key, value) {
      if (!this.data[key]) {
        this.$set(this.data, key, value)
      }
    },

    handleCountyPass() {
      if (!this.validator() || !this.validatorOption()) return

      const data = this.setStatus(1)
      // 比较 审批（建议）金额 与 审批授权金额：
      //  - 如果小于审批授权金额，则需要区县农 担业务、风控、负责人（三部门） 审批，在区县负责人审批通过时，自动修改省担保所有状态为通过
      //  - 如果大于审批授权金额，则不需要区县后继三部门审批，在项目经理通过时，自动修改 区县三部门 和 省项目经理 审批状态为通过
      // const resFunds = +(this.data.res_funds || this.data.approved_funds)
      // const isAutoApprovalProject = this.isUnionProvince && resFunds <= this.provinceCreditAmount
      const autoData = this.isAutoApprovalProject
        ? this.getAutoProvinceApprovalData()
        : this.getAutoCountyApprovalData()

      data.process_status = this.isAutoApprovalProject ? 0 : 1
      data.project_status = 1
      this.updateData(
        '确定通过?',
        {
          ...data,
          ...autoData,
        },
        'info'
      )
    },

    handleCountyReject() {
      this.refuseType = 'city'
      this.refuseVisible = true
    },

    updateData(message, data, type = 'info') {
      this.$utils
        .msgbox({
          message,
          type,
          beforeClose: () =>
            this.$api.updateData(this.$serviceName, this.tableName, this.relatedId, data),
        })
        .then(() => {
          this.$message.success('操作成功！')
          this.$emit('success', false)
          this.refuseBeforeClose()
        })
        .catch(() => this.$message.error(`操作失败，请重试！`))
    },

    // 省联担，小于等于审批授权金额的项目自动审批
    getAutoProvinceApprovalData() {
      if (this.editEnableCorp) {
        const dateNow = this.$utils.dateFormat(new Date())
        return {
          city_res_status: 1,
          city_res_date: dateNow,
          city_res_status_bus: 1,
          city_res_date_bus: dateNow,
          city_res_status_risk: 1,
          city_res_date_risk: dateNow,
          city_res_status_corp: 1,
          city_res_date_corp: dateNow,
        }
      }
      return {}
    },

    // 省联担，大于审批授权金额的项目，在区县端只需要项目经理填写意见，其余自动通过
    // 需要到省担保去审批
    getAutoCountyApprovalData() {
      if (this.editEnableAb) {
        const dateNow = this.$utils.dateFormat(new Date())
        return {
          res_status_bus: 1,
          res_date_bus: dateNow,
          res_status_risk: 1,
          res_date_risk: dateNow,
          res_status_corp: 1,
          res_date_corp: dateNow,
          city_res_status: 1,
          city_res_date: dateNow,
        }
      }
      return {}
    },

    setStatus(num, message) {
      const data = {}
      const dateNow = this.$utils.dateFormat(new Date())

      if (this.editEnableBusiness) {
        data.res_status_bus = num
        data.res_date_bus = dateNow
        data.res_person_bus = this.user.realName
        data.res_option_bus = message || this.data.res_option_bus
        data.res_funds = this.data.res_funds

        const msg = message || this.data.res_option
        if (this.editEnableAb && this.related.res_option !== msg) {
          data.res_date = dateNow
          data.res_option = msg
        }
      } else if (this.editEnableAb) {
        data.res_status = num
        data.res_date = dateNow
        data.res_person = this.user.realName
        data.res_option = message || this.data.res_option
        data.res_funds = this.data.approved_funds
        data.res_person_user_id = this.userId
      }

      if (this.editEnableRisk) {
        data.res_status_risk = num
        data.res_date_risk = dateNow
        data.res_person_risk = this.user.realName
        data.res_option_risk = message || this.data.res_option_risk
        data.res_funds = this.data.res_funds
      }
      if (this.editEnableCorp) {
        data.res_status_corp = num
        data.res_date_corp = dateNow
        data.res_person_corp = this.user.realName
        data.res_option_corp = message || this.data.res_option_corp
        data.res_funds = this.data.res_funds
      }

      data.load_rate = this.data.load_rate
      data.approved_funds = this.data.approved_funds
      data.approval_load_years = this.data.approval_load_years
      data.gua_rate = this.data.gua_rate
      data.approval_fee = this.data.approval_fee
      data.project_des = this.data.project_des
      data.counter_guarantee = this.data.counter_guarantee

      return data
    },

    validatorOption() {
      if (this.editEnableAb && !this.data.res_option) {
        this.$message.warning('请输入项目经理意见')
        return false
      }
      if (this.editEnableBusiness && !this.data.res_option_bus) {
        this.$message.warning('请输入业务部意见')
        return false
      }
      if (this.editEnableRisk && !this.data.res_option_risk) {
        this.$message.warning('请输入风控部意见')
        return false
      }
      // 负责人意见是否可编辑
      if (this.editEnableCorp && !this.data.res_option_corp) {
        this.$message.warning('请输入负责人意见')
        return false
      }
      return true
    },

    validator() {
      if (!this.data.approved_funds && this.isAbApproval) {
        this.$message.error('请输入建议金额！')
        return false
      }
      if (!this.data.res_funds && !this.isAbApproval) {
        this.$message.error('请输入审批金额！')
        return false
      }
      const validatePairs = {
        load_rate: '请输入基准利率！',
        approval_load_years: '请输入期限！',
        gua_rate: '请输入担保费率！',
        approval_fee: '请输入评审费！',
        counter_guarantee: '请输入反担保措施！',
        project_des: '请输入项目基本介绍！',
      }

      for (const key in validatePairs) {
        if (!this.data[key]) {
          this.$message.error(validatePairs[key])
          return false
        }
      }

      return true
    },

    handleProvincePass() {
      if (!this.validatorProvinceOption()) return

      const data = this.getProvinceUpdateData(1)
      this.updateData('确定通过?', data, 'info')
    },

    handleProvinceReject() {
      this.refuseType = 'province'
      this.refuseVisible = true
    },

    handleRefuseConfirm() {
      if (!this.refuseReason) {
        return this.$message.error('请输入拒绝理由')
      }

      if (this.refuseType === 'city') {
        const data = this.setStatus(2, this.refuseReason)
        this.updateData('确定不通过?', data, 'error')
      } else {
        const data = this.getProvinceUpdateData(2, this.refuseReason)
        this.updateData('确定不通过?', data, 'error')
      }
    },

    refuseBeforeClose() {
      this.refuseReason = ''
      this.refuseVisible = false
    },

    getProvinceUpdateData(num, message) {
      const data = {}
      const dateNow = this.$utils.dateFormat(new Date())

      if (this.editEnableBusinessProvince) {
        data.city_res_status_bus = num
        data.city_res_date_bus = dateNow
        data.city_res_person_bus = this.user.realName
        data.city_res_option_bus = message || this.data.city_res_option_bus
      }
      if (this.editEnableRiskProvince) {
        data.city_res_status_risk = num
        data.city_res_date_risk = dateNow
        data.city_res_person_risk = this.user.realName
        data.city_res_option_risk = message || this.data.city_res_option_risk
      }
      if (this.editEnableCorpProvince) {
        data.city_res_status_corp = num
        data.city_res_date_corp = dateNow
        data.city_res_person_corp = this.user.realName
        data.city_res_option_corp = message || this.data.city_res_option_corp
      }

      return data
    },

    validatorProvinceOption() {
      if (this.editEnableBusinessProvince && !this.data.city_res_option_bus) {
        this.$message.warning('请输入省业务部意见')
        return false
      }
      if (this.editEnableRiskProvince && !this.data.city_res_option_risk) {
        this.$message.warning('请输入省风控部意见')
        return false
      }
      if (this.editEnableCorpProvince && !this.data.city_res_option_corp) {
        this.$message.warning('请输入省负责人意见')
        return false
      }
      return true
    },

    handlePrint() {
      printHtml(
        document.getElementById('print-wrap').innerHTML,
        `
        .vertical-align-middle td {vertical-align: middle;}
      `
      )
    },
  },
}
</script>

<style lang="scss" scoped>
.vertical-align-middle td {
  vertical-align: middle;
}
.bg-gray {
  background-color: $gray-200;
}
</style>
